﻿using System;
using AutoKoC.Models;
using CSharp.Libs.Koc;
using CSharp.Libs.WPF;
using System.Collections;
using System.Text;
using System.Windows.Input;



namespace AutoKoC.ViewModels
{
    class AverageMightViewModel : ViewModelBase
    {
        #region declarations
        private AppBase _AB = null;

        private RelayCommand _rcGetAverageMight = null;

        private Int32 _intNumberOfPages = 1;
        private String _strResult = "";
        #endregion



        #region constructor / terminator
        public AverageMightViewModel(
            AppBase AB)
        {
            _AB = AB;

            _AB.TM.FbParametersChanged += new TrafficMonitor.FbParametersChangedEventHandler(TM_FbParametersChanged);
        }

        ~AverageMightViewModel()
        {
            if(_AB != null)
            {
                if(_AB.TM != null)
                {
                    _AB.TM.FbParametersChanged -= TM_FbParametersChanged;
                }

                _AB = null;
            }
        }
        #endregion



        #region event handling
        void TM_FbParametersChanged(object sender)
        {
            if(_AB.DataIsValid)
            {
                _PreparePhpCommands();
            }
        }
        #endregion



        #region private functions
        /// <summary>_PreparePhpCommands
        /// 
        /// </summary>
        private void _PreparePhpCommands()
        {
            try
            {
                if(!_AB.UH.URLAllianceGetOtherInfo.URLMaybeValid)
                {
                    //Generate Command (without own parameters -> myServers.php) out of getChat.php
                    _AB.UH.ParseURLAllianceGetOtherInfo(_AB.UH.URLGetChat.GetURL().Replace(URLHolder.PHP_GET_CHAT, URLHolder.PHP_ALLIANCE_GET_OTHER_INFO));
                    
                    //Remove getChat.php specific parameters
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CTYPE);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CTYPE_ID);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_1);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_2);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_3);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Remove(URLHolder.PARAM_SID);

                    //Add allianceGetOtherInfo specific parameters
                    String strCityID = "";
                    if(_AB.BSVM.Cities.Count > 0)
                    {
                        strCityID = _AB.BSVM.Cities[0].CityID.ToString();
                    }
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Add(URLHolder.PARAM_CITY_ID, strCityID);
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.Add(URLHolder.PARAM_PAGE_NO, "1");
                }
            }
            catch(Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
                throw;
            }
        }

        /// <summary>_GetAverageMight
        /// 
        /// </summary>
        private void _GetAverageMight()
        {
            try
            {
                //Check if URL is valid
                if(_AB.UH.URLAllianceGetOtherInfo.URLMaybeValid &&
                   _AB.UH.URLAllianceGetOtherInfo.Parameters.ContainsKey(URLHolder.PARAM_PAGE_NO))
                {
                    //Clear previous result
                    _strResult = "";
                    Int32 Rank = 1;

                    //Create Header
                    String strfrmAlliList = "{4,3} {0,-30}{1,-20}{2,-10}{3,10}";

                    _strResult = String.Concat(
                        _strResult,
                        String.Format(strfrmAlliList, "Alliance Name", "Might", "Members", "Average", "No."),
                        Environment.NewLine);
                    _strResult = String.Concat(
                        _strResult,
                        "------------------------------------------------------------------------------------",
                        Environment.NewLine);

                    for (Int32 PageNo = 1; PageNo <= _intNumberOfPages; PageNo++)
                    {
                        //Set Parameters for URL
                        _AB.UH.URLAllianceGetOtherInfo.Parameters[URLHolder.PARAM_PAGE_NO] = PageNo.ToString();

                        //Prepare Answer-Hashtable
                        Hashtable Allis = null;
                        if (_AB.UH.URLAllianceGetOtherInfo.GetAnswerHashtable(out Allis))
                        {
                            //Check if Answer is correct
                            if (Allis.ContainsKey(constants.KEY_OTHER_ALLIANCES))
                            {
                                //Get Result-ArrayList
                                ArrayList AlliList = (ArrayList)Allis[constants.KEY_OTHER_ALLIANCES];

                                //Cycle trough Allis
                                foreach (Hashtable htAlli in AlliList)
                                {
                                    Int32 Schnitt = Int32.Parse(htAlli[constants.KEY_MIGHT].ToString()) / Int32.Parse(htAlli[constants.KEY_MEMBERS_COUNT].ToString());

                                    _strResult = String.Concat(
                                        _strResult,
                                        String.Format(strfrmAlliList,
                                            htAlli[constants.KEY_NAME],
                                            Int32.Parse(htAlli[constants.KEY_MIGHT].ToString()).ToString("0,000"),
                                            htAlli[constants.KEY_MEMBERS_COUNT],
                                            Schnitt.ToString("0,000"),
                                            Rank.ToString()),
                                        Environment.NewLine);

                                    Rank++;
                                }
                            }

                            //Write Result to Console
                            //_strResult = SB.ToString();
                        }
                        else
                        {
                            _strResult = "Something went wrong. :(";
                        }
                    }
                }
                else
                {
                    _strResult = "UPS. URL is NOT valid?";
                }

                OnPropertyChanged("Result");
            }
            catch(Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }
        #endregion



        #region interface
        #region properties
        public ICommand GetAverageMight
        {
            get
            {
                if(_rcGetAverageMight == null)
                {
                    _rcGetAverageMight = new RelayCommand(
                        param => this._GetAverageMight(),
                        param => this.CanGetAverageMight);
                }
                return _rcGetAverageMight;
            }
        }
        public Boolean CanGetAverageMight
        {
            get
            {
                return
                    _AB.UH.URLAllianceGetOtherInfo.URLMaybeValid &&
                    _AB.UH.URLAllianceGetOtherInfo.Parameters.ContainsKey(URLHolder.PARAM_PAGE_NO);
            }
        }

        public Int32 NumberOfPages
        {
            get
            {
                return _intNumberOfPages;
            }
            set
            {
                if (value > 0 && value < 999)
                {
                    _intNumberOfPages = value;
                }
            }
        }

        public String Result
        {
            get
            {
                return _strResult;
            }
        }
        #endregion

        #region methods

        #endregion
        #endregion
    }
}
